<?php
/**
 * Created by PhpStorm.
 * User: wendy
 * Date: 16-9-20
 * Time: 16:20
 */
namespace Common\Model;

class UserAmountModel extends VRUserModel{

    public $taskArr = array(
        '1' => 1,
        '2' => 5,
        '3' => 5,
        '4' => 5,
        '5' => 2,
    );
    /**
     * 获取用户金币明细
     */
    public function getUserAmountList($user_id, $page, $size){
        $offset = $size*($page - 1);
        $data['list']  = $this->where(array('user_id'=>$user_id))->order("created_at desc")->limit($offset,$size)->select();
        $data['count'] = $this->where(array('user_id'=>$user_id))->count();
        return $data;
    }

    /**
     * 用户消费记录
     */
    public function addUserAmount($param){
        $user = new UserModel();
        $user_info = $user->where(array('user_id'=>$param['user_id']))->find();
        if(!$user_info){
            return false;
        }
        if(!empty($param['task_id'])){ //做任务
            $user_task = M("vruser1.user_task",null);
            $where['user_id'] = array('eq',$param['user_id']);
            $where['task_id'] = array('eq',$param['task_id']);
            $where['created_at'] = array(array('EGT', date('Y-m-d',time()).' 00:00:00'),array('LT', date('Y-m-d',time()).' 23:59:59'));
            $count = $user_task->where($where)->count();
            if($count < $this->taskArr[$param['task_id']]){
                $task_data['task_id'] = $param['task_id'];
                $task_data['user_id'] = $param['user_id'];
                $task_data['amount']  = $param['operate_cnt'];
                $task_data['created_at'] = date('Y-m-d H:i:s', time());
                $task_data['user_task']  = time().rand(0,9);
                $user_task->add($task_data);
            }else{
                return false;
            }
        }
        $user_amount = new UserAmountModel();
        $user_data = array();
        $data['user_id'] = $param['user_id'];
        $data['operate_cnt'] = $param['operate_cnt'];
        if($param['operate'] == 1){ //获得
            $data['surplus'] = $user_info['amount'] + $param['operate_cnt'];
            $user_data['amount'] = $user_info['amount'] + $param['operate_cnt']; //更新用户的汇闻币总数
        }elseif ($param['operate'] == 2){ //消耗
            if($user_info['amount'] < $param['operate_cnt']){
                return false;
            }
            $data['surplus'] = $user_info['amount'] - $param['operate_cnt'];
            $user_data['amount'] = $user_info['amount'] - $param['operate_cnt']; //更新用户的汇闻币总数
        }
        $data['operate'] = $param['operate'];
        $data['operate_name'] = $param['operate_name'];
        $data['created_at']   = date('Y-m-d H:i:s', time());
        $user_amount->add($data); //增加记录
        $user->where(array('user_id'=>$param['user_id']))->save($user_data); //更新用户表汇闻币
        return array('amount'=>$user_data['amount']);
    }
}